package com.zy.fee.roadpark.activity.nb;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.flyco.roundview.RoundTextView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.CommonLogic;
import com.zy.fee.roadpark.dao.NbNodeLogic;
import com.zy.fee.roadpark.dao.NbNodeRecordLogic;
import com.zy.fee.roadpark.model.M_Node;
import com.zy.fee.roadpark.model.M_NodeRecord;
import com.zy.fee.roadpark.model.apimodel.APIM_NodeRecordInfo;
import com.zy.fee.roadpark.model.apimodel.APIM_NodeRecordList;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.config.LibraryConstants;
import com.zygk.library.model.CommonResult;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.ImageUtil;
import com.zygk.library.util.ListUtils;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.LibraryCommonDialog;
import com.zygk.library.view.XKeyboardView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Wikison on 2018/9/17.
 * 取证
 */
public class NbForensicsActivity extends BaseActivity {

  @BindView(R.id.iv_right) ImageView ivRight;
  @BindView(R.id.ll_right) LinearLayout llRight;
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.et_code) EditText etCode;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.iv_photo) ImageView ivPhoto;
  @BindView(R.id.tv_time) TextView tvTime;
  @BindView(R.id.tv_button) RoundTextView tvButton;
  @BindView(R.id.view_keyboard) XKeyboardView viewKeyboard;

  private ArrayList<ImageItem> images = null;
  private String carPath = "";
  private M_Node mNode;
  private String code, plateNumber, pic;
  private boolean isReForensics;
  private String originPlateNumber = "";

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_nb_forensics);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    initImagePickerSingle(false);

    mNode = (M_Node) getIntent().getSerializableExtra(NbSpotListActivity.INTENT_NODE);

    isReForensics =
        getIntent().getBooleanExtra(NbRegistrationPlateActivity.INTENT_IS_FORENSIC, false);
    originPlateNumber = getIntent().getStringExtra(NbRegistrationPlateActivity.INTENT_ORIGIN_PLATE);
  }

  private void initView() {
    lhTvTitle.setText("取证");

    if (mNode != null) {
      code = mNode.getCode();
      etCode.setText(code);
      etCode.setEnabled(false);
      plateNumber = mNode.getCarNumber();
      gpvPlateNumber.setPassword(plateNumber);
      if (mNode.getShowState() == 1 && isReForensics) {
        searchRecordNoPay();
      }
      tvTime.setText(mNode.getShowState() == 0 ? "00:00:00"
          : DateTimeUtil.getSecondsFormat(mNode.getSeconds()));
    }
  }

  private void initListener() {
    viewKeyboard.setIOnKeyboardListener(new XKeyboardView.IOnKeyboardListener() {
      @Override public void onInsertKeyEvent(String text) {
        gpvPlateNumber.appendPassword(text);
      }

      @Override public void onDeleteKeyEvent() {
        gpvPlateNumber.deletePassword();
      }
    });

    gpvPlateNumber.togglePasswordVisibility();

    gpvPlateNumber.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
      @Override public boolean beforeInput(int position) {
        viewKeyboard.setVisibility(View.GONE);
        return true;
      }

      @Override public void onTextChanged(String psw) {
      }

      @Override public void onInputFinish(String psw) {
      }
    });

    etCode.setOnFocusChangeListener((view, hasFocus) -> {
      if (hasFocus) {
        viewKeyboard.setVisibility(View.GONE);
      } else {
        InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
      }
    });
  }

  private void searchRecordNoPay() {
    NbNodeRecordLogic.nbnode_searchrecord_unpay(mContext,
        PreferencesHelper.userManager().getUserID(), code, originPlateNumber,
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_NodeRecordInfo result = (APIM_NodeRecordInfo) obj;
            M_NodeRecord nodeRecord = result.getNodeRecordInfo();
            pic = nodeRecord.getPic();
            imageManager.loadUrlImage(pic, ivPhoto);
            tvTime.setText(DateTimeUtil.getMinutesFormat(nodeRecord.getMin()));
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      //添加图片返回
      if (data != null && requestCode == REQUEST_CODE_SELECT) {
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        String originImage = images.get(0).path;

        FileInputStream fis = null;
        try {
          fis = new FileInputStream(originImage);
          Bitmap bitmap = BitmapFactory.decodeStream(fis);

          if (null == bitmap) {
          } else {
            if (addWatermarkBitmap(bitmap, DateTimeUtil.getCurrentTime(), bitmap.getWidth(),
                bitmap.getHeight())) {
            } else {
              ToastUtil.showMessage(mContext, "水印添加失败");
              carPath = originImage;
            }
          }
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }
      }
    }
  }

  private boolean addWatermarkBitmap(Bitmap bitmap, String strMark, int w, int h) {
    int destWidth = w;   //此处的bitmap已经限定好宽高
    int destHeight = h;

    Bitmap carBitmap =
        Bitmap.createBitmap(destWidth, destHeight, Bitmap.Config.ARGB_8888); //定好宽高的全彩bitmap
    Canvas canvas = new Canvas(carBitmap);//初始化画布绘制的图像到icon上

    Paint photoPaint = new Paint(); //建立画笔
    photoPaint.setDither(true); //获取跟清晰的图像采样
    photoPaint.setFilterBitmap(true);//过滤一些

    Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());//创建一个指定的新矩形的坐标
    Rect dst = new Rect(0, 0, destWidth, destHeight);//创建一个指定的新矩形的坐标
    canvas.drawBitmap(bitmap, src, dst, photoPaint);//将photo 缩放或则扩大到 dst使用的填充区photoPaint

    Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//设置画笔
    textPaint.setTextSize(destWidth / 20);//字体大小
    textPaint.setTextAlign(Paint.Align.CENTER);
    textPaint.setTypeface(Typeface.DEFAULT_BOLD);//采用默认的宽度
    textPaint.setAntiAlias(true);  //抗锯齿
    textPaint.setStrokeWidth(3);
    textPaint.setAlpha(15);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(Color.RED);//水印文字颜色
    textPaint.setShadowLayer(1f, 0f, 3f, Color.LTGRAY);
    canvas.drawText(strMark, destWidth / 3, 100, textPaint);//绘制上去字，开始未知x,y采用那只笔绘制
    canvas.save();
    canvas.restore();
    bitmap.recycle();

    carPath = LibraryConstants.SAVE_IMAGE_PATH_IMGS + DateTimeUtil.getCurrentTime() + ".jpg";
    imageManager.loadLocalImage(carPath, ivPhoto);

    try {
      ImageUtil.saveImage(carBitmap, carPath);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  private void uploadPic() {
    String fileName = UUID.randomUUID().toString() + carPath.substring(carPath.lastIndexOf("."));

    CommonLogic.do_upload_pic(mContext, true, carPath, fileName, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        CommonResult result = (CommonResult) obj;
        pic = result.getData();
        node_edit();
      }

      @Override public void onFailed() {

      }

      @Override public void onFinish() {

      }
    });
  }

  private void node_edit() {
    NbNodeLogic.node_edit(mContext, code, plateNumber, pic, new HttpRequest.HttpCallback() {
      @Override public void onStart() {

      }

      @Override public void onSucceed(Object obj) {
        sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
        sendBroadcast(new Intent(Constants.BROADCAST_FORENSICS_SUCCESS));
        ToastUtil.showMessage(mContext, "提交成功");
        //查询追缴
        record_no_pay_list();
      }

      @Override public void onFailed() {

      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  private void record_no_pay_list() {
    NbNodeRecordLogic.nbnode_record_unpay_list(mContext, plateNumber, 1, Constants.ROWS,
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_NodeRecordList result = (APIM_NodeRecordList) obj;
            if (ListUtils.isEmpty(result.getNodeRecordList())) {
              finish();
            } else {
              if (hasRecordList(result.getNodeRecordList())) {
                LibraryCommonDialog.showYesOrNoDialog(mContext, "追缴提示", plateNumber + "有历史未缴费单据需追缴",
                    "取消", "进入追缴页面", () -> {
                      Intent intent = new Intent(mContext, NbOverpayBillListActivity.class);
                      intent.putExtra(NbOverpayBillListActivity.INTENT_PLATE_NUMBER, plateNumber);
                      startActivity(intent);
                      finish();
                    }, () -> {
                      finish();
                    });
              } else {
                finish();
              }
            }
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private boolean hasRecordList(List<M_NodeRecord> nodeRecordList) {
    boolean result = false;
    for (int i = 0; i < nodeRecordList.size(); i++) {
      if (nodeRecordList.get(i).getState() == 1) {
        result = true;
        break;
      }
    }
    return result;
  }

  @OnClick({
      R.id.ll_back, R.id.ll_right, R.id.iv_photo, R.id.tv_button
  }) public void onViewClicked(View view) {
    Intent intent;
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.iv_photo:
        viewKeyboard.setVisibility(View.GONE);
        picOne();
        break;
      case R.id.tv_button:
        if (mNode != null && mNode.getIsPay() == 1) {
          ToastUtil.showMessage(mContext, "该车已付款, 无需再取证");
          return;
        }
        code = etCode.getText().toString();
        plateNumber = gpvPlateNumber.getPassWord();
        if (!StringUtils.isBlank(code) && !StringUtils.isBlank(plateNumber)) {
          if (!StringUtils.isBlank(carPath)) {
            showCommitDialog();
          } else {
            if (!StringUtils.isBlank(pic)) {
              showCommitDialog();
            } else {
              ToastUtil.showMessage(mContext, "请上传图片");
            }
          }
        } else {
          ToastUtil.showMessage(mContext, "请输入车位号和车牌号");
        }
        break;
      case R.id.ll_right:
        if (mNode.getShowState() == 1) {
          intent = new Intent(mContext, NbReceivablesActivity.class);
          intent.putExtra(NbReceivablesActivity.INTENT_CODE, code);
          intent.putExtra(NbReceivablesActivity.INTENT_PLATE_NUMBER, plateNumber);
          startActivity(intent);
        }
        break;
    }
  }

  private void showCommitDialog() {
    LibraryCommonDialog.showYesOrNoDialog(mContext, "", "确认提交", "取消", "确认", () -> {
      if (!StringUtils.isBlank(carPath)) {
        //上传图片后
        uploadPic();
      } else {
        node_edit();
      }
    }, () -> {

    });
  }
}
